#coding=utf-8

import json
import socket

class TCP_Json_Interface:
    '''
        基于TCP-Json的消息接口
    '''
    def __init__(self,ip="192.168.0.199",port=8000):
        '''
        初始化
        '''
        self.sync_Upload={}
        self.sync_Download={}
        #   配置信息
        self.ip=ip
        self.port=port

    def AquireWifiList(self):
        '''
        检索Wifi列表
        :return: Wifi列表
        '''
        datBundle={"type":"wifi_list"}
        return self.SyncDat(datBundle)

    def SetStation(self,ssid,passwd,ip,mask,gate,clear=0):
        '''
        配置机器的Station模式（让机器连接到热点）
        :param ssid:
        :param passwd:
        :param ip:
        :param mask:
        :param gate:
        :param clear: 是否要清空连接信息【0：写入  1：清空】
        :return:
        '''
        datBundle={"type":"con_ap","ssid":ssid,"passwd":passwd,"ip":ip,"mask":mask,"gate":gate,"clear":clear}
        return self.SyncDat(datBundle)

    def JControl(self,jL=[0.0,0.0,0.0,0.0,0.0],jR=[0.0,0.0,0.0,0.0,0.0]):
        '''
        控制双足运动
        :param jL:
        :param jR:
        :return:
        '''
        datBundle={"type":"joint","l":jL,"r":jR}
        return self.SyncDat(datBundle)

    def J_Calibrate(self,jL=[0.0,0.0,0.0,0.0,0.0],jR=[0.0,0.0,0.0,0.0,0.0]):
        '''
        校正机器人各个关节的零点
        :return:
        '''
        datBundle = {"type": "j_calib", "l": jL, "r": jR}
        print(datBundle)
        return self.SyncDat(datBundle)

    def SyncDat(self,datPush):
        '''
        与服务器同步数据
        :param datPush:
        :return:
        '''
        sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(3.0)
        try:
            sock.connect((self.ip,self.port))
            sock.sendall(json.dumps(datPush).encode())
            recv=sock.recv(256)
            return json.loads(recv)
        except Exception as e:
            return {"type":"fail","data":e}